package com.guigu.tms.oms.service.impl;

import com.guigu.tms.commons.order.entity.Rule;
import com.guigu.tms.commons.order.entity.fact.AddressCheckResult;
import com.guigu.tms.commons.order.entity.fact.AddressRule;
import com.guigu.tms.oms.mapper.RuleMapper;
import com.guigu.tms.oms.service.IRuleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieRepository;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zwj
 * @since 2022-09-27
 */
@Service
public class RuleServiceImpl extends ServiceImpl<RuleMapper, Rule> implements IRuleService {


    @Autowired
    private RuleMapper ruleMapper;

    public static KieContainer kieContainer;

    public BigDecimal rule(AddressRule rule){
        KieSession kieSession=kieContainer.newKieSession();
        System.out.println(rule);

        kieSession.insert(rule);
        AddressCheckResult addressCheckResult = new AddressCheckResult();
        kieSession.insert(addressCheckResult);
        kieSession.fireAllRules();
        kieSession.dispose();
        return new BigDecimal(addressCheckResult.getResult());
    }

    @Override
    public List<Rule> loadRules() {
        return ruleMapper.selectList(null);
    }

    @Override
    public boolean reload() {
        KieContainer kieContainer=loadKieContainer(loadRules());
        this.kieContainer=kieContainer;
        return true;
    }

    /**
     * 根据规则内容创建kieContainer容器
     * @param rules
     * @return
     */
    public KieContainer loadKieContainer(List<Rule> rules){
        KieServices ks=KieServices.Factory.get();
        KieRepository kr=ks.getRepository();
        KieFileSystem kfs = ks.newKieFileSystem();
        for (Rule rule : rules) {
            String drl=rule.getContent();
            kfs.write("src/main/resources/rules/"+drl.hashCode()+".drl",drl);
        }
        KieBuilder kb = ks.newKieBuilder(kfs);
        kb.buildAll();
        KieContainer kieContainer = ks.newKieContainer(kr.getDefaultReleaseId());
        return kieContainer;
    }
}
